from flask import Flask, request, render_template, redirect, url_for, session

app = Flask(__name__)
# 要使用session就要定义一个secret_key
app.secret_key = 'xxxxss22'
DATA_DICT={
    1:{'name':'拉拉','age':18},
    2:{'name':'哈哈','age':18}
}
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    # 处理 POST 请求
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    if user == 'keshufang' and pwd == '666':
        session['xxx'] = 'keshufang'
        return redirect('/index')
    error = '用户名或者密码错误'
    return render_template('login.html',error=error)
# endpoint='idx'相当于路由加了个name
@app.route('/index',endpoint='idx')
def index():
    # 读取session
    username = session.get('xxx')
    if not username:
        return redirect(url_for('login'))
    data_dict = DATA_DICT
    return render_template('index.html',data_dict=data_dict)
# 提交是post请求，所以要在这边加上post
@app.route('/edit',methods=['GET','POST'])
def edit():
    nid = request.args.get('nid')
    nid = int(nid)
    if request.method=="GET":
        info = DATA_DICT[nid]
        # 一点编辑就可以编辑页
        # html的value把默认可以编辑的值放进来
        return render_template('edit.html',info=info)
    user = request.form.get('user')
    age = request.form.get('age')
    DATA_DICT[nid]['name'] = user
    DATA_DICT[nid]['age'] = age
    return redirect(url_for('idx'))

# 接受一个值，如果内部转换为int类型，<int:nid>，不然默认是字符串类型
@app.route('/del/<int:nid>')
def delete(nid):
    # del关键字删除DATA_DICT中指定 nid 对应的数据项
    del DATA_DICT[nid]
    # return redirect('/index')
    return redirect(url_for("idx"))
if __name__ == '__main__':
    app.run(debug=True)